<template>
    <div class="ckeditor">
        <textarea :id="id" :value="value"></textarea>
    </div>
</template>

<script type="text/ecmascript-6">
    export default{
        props: {
            value: {
                type: String
            },
            id: {
                type: String,
                default: 'editor'
            },
            height: {
                type: String,
                default: '200px'
            },
            toolbar: {
                type: Array,
                default: () => [
                    [ 'Format' ], [ 'Bold', 'Italic', 'Strike' ], [ 'NumberedList', 'BulletedList' ],
                    [ 'Copy', 'Paste' ], [ 'PasteText', 'PasteFromWord', 'Outdent', 'Indent' ], [ '-' ], [ 'Undo', 'Redo' ],
                    [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ], [ 'Source' ]
                ]
            },
            language: {
                type: String,
                default: 'en'
            },
            extraplugins: {
                type: String,
                default: ''
            }
        },
        beforeUpdate () {
            const ckeditorId = this.id

            if (this.value !== CKEDITOR.instances[ckeditorId].getData()) {
                CKEDITOR.instances[ckeditorId].setData(this.value)
            }
        },
        mounted () {
            const that = this
            const ckeditorId = this.id
            const ckeditorConfig = {
                toolbar: this.toolbar,
                language: this.language,
                height: this.height,
                extraPlugins: this.extraplugins
            }
            CKEDITOR.replace(ckeditorId, ckeditorConfig)
            CKEDITOR.instances[ckeditorId].setData(this.value)
            CKEDITOR.instances[ckeditorId].on('change', function () {
            let ckeditorData = CKEDITOR.instances[ckeditorId].getData()
            if (ckeditorData !== this.value)
                {
                    that.modify(ckeditorData)
                }
            })
        },
        destroyed()
        {
            const ckeditorId = this.id
            if (CKEDITOR.instances[ckeditorId]) {
                CKEDITOR.instances[ckeditorId].destroy()
            }
        },
        methods: {
            modify (ckeditorData) {
                this.$emit('input', ckeditorData)
            }
        }
    }
</script>
<style>
    .ckeditor {
        width: 100%;
        clear: both;
    }
</style>
